/**
  ******************************************************************************
  * File Name          : thapp.c
  * Description        : This file provides code for the configuration
  *                      of the lora e22-400t22s instances.
  ******************************************************************************
  * @attention
  *
  ******************************************************************************
  */
#include "tskcfg.h"
#include "bsp.h"
#include "sensor.h"
#include "edct.h"
#include "si2c_comm.h"

/* T&H Sensor task */
TaskHandle_t xSdp810_Thd = NULL;
StaticTask_t xSdp810_Tcb;
StackType_t  xSdp810_Stk[ SDP810_STACK_SIZE ];
void vSdp810_Task( void * pvParameters );

typedef struct
{
	volatile int16_t pressure;
}SDP810_DataType;

static uint8_t sdp810_check_rational(float pressure)
{
	if((pressure < -500) || (pressure > 500))
	{
		return 1;
	}
  
	return 0;
}

static void sdp810_measure(void)
{
	uint8_t err;
	static uint8_t fail_sdp810 = 0;
	uint8_t active_sdp810 = 0;
	volatile SDP810_DataType sdp810_data;

	err = Sdp810_GetSingleMeasure(&sdp810_data.pressure);
	if(err == 0)
	{
		active_sdp810 = 1;
    fail_sdp810 = 0;
	}
	else
	{
		active_sdp810 = 0;
		fail_sdp810++;
		printf("sdp810 err:%d\r\n", err);
	}
	
	if((active_sdp810 != 0) && (sdp810_check_rational(sdp810_data.pressure) == 0))
	{
		SENSOR.Status_Pres = 1;
		SENSOR.pressure = sdp810_data.pressure;
	}
	else
	{
		SENSOR.Status_Pres = 0;
	}
  
	if((fail_sdp810 == 20) || (fail_sdp810 == 30) || (fail_sdp810 == 40))
	{
    Sdp810_ResetCmd();
    
    Sdp810_ReInit();
    
    printf("SDP810 Soft reset!\r\n");
  }
  else if(fail_sdp810 > 66)
  {
    SENSOR.Status_Pres = 0;
		SENSOR.pressure = 0;
    
    sI2c_IOPowerReset();
    
		fail_sdp810 = 0;
    
		printf("SDP810 Reset power!\r\n");
	}
}

void vSdp810_Task( void * pvParameters )
{
  TickType_t xLastWakeTime;
  
  xLastWakeTime = xTaskGetTickCount();
  
	while(1)
	{
    if(xTaskDelayUntil(&xLastWakeTime, 500) == pdFALSE)
    {
      vTaskDelay(500);
      xLastWakeTime = xTaskGetTickCount();
    }

#ifndef EDCT_JUST_PRESS
    if(Edct_RunPara.sdp810_en == 1)
#endif
    {
      sdp810_measure();
    }
	}
}
